package com.zr.websocket;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

//实时更新异常信息webSocket
@Component
@ServerEndpoint(value = "/abnormalSocket/{token}")
public class AbnormalSocket {

    //存取在线连接socket的用户
    private static Map<String, Session> sessionMap=new HashMap<>();

    //用户令牌
    private String token;

    //用户socket的session
    private Session session;


    /**
     * @author wanglu
     * 连接socket时用户存入静态属性map
     * @param session
     * @param token
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value="token")String token) {
        this.session = session;//前端创建连接时记录登录用户session，存入静态属性
        this.token=token;
        AbnormalSocket.sessionMap.put(token, session);
    }

    /**
     * @author wanglu
     * 前端关闭连接时，移除session
     */
    @OnClose
    public void onClose() {
        AbnormalSocket.sessionMap.remove(this.token);
    } //前端关闭连接时，移除session

    /**
     * @author wanglu
     * 向指定用户或全部在线用户发送消息
     * @param toUserId
     * @param text
     */
    public static void send(String toUserId, String text){
        Set<String> keySet = AbnormalSocket.sessionMap.keySet();
        if(StringUtils.hasLength(toUserId) && keySet.contains(toUserId)){
            AbnormalSocket.sessionMap.get(toUserId).getAsyncRemote().sendText(text);  //发送消息
        }else {
            for(String s: keySet){
                AbnormalSocket.sessionMap.get(s).getAsyncRemote().sendText(text);  //所有人发送消息
            }
        }

    }

}
